const mongoose = require('mongoose')
const UserSchema = mongoose.model('UserSchema')
const Router = require('koa-router')
const UserRouter = new Router()
UserRouter.post('/register', async ctx => {
  const { body } = ctx.request
  try {
    const res = await UserSchema.findOne({ userName: body.userName }).exec()
    if (res) {
      return ctx.body = {
        code: 500,
        msg: '用户名已经注册'
      }
    }
    const newUser = await new UserSchema(body).save()
    ctx.cookies.set('userId', newUser._id, {
      path: '/',
      httpOnly: false,
      overwrite: false,
      maxAge: 10 * 60 * 1000 //ms
    })
    ctx.body = {
      code: 200,
      msg: '注册成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      msg: '注册失败'
    }
  }
})

UserRouter.post('/login', async ctx => {
  try {
    const { body } = ctx.request
    const res = await UserSchema.findOne({userName: body.userName, password: body.password}, { password: 0 })
    if (!res) {
      return ctx.body = {
        code: 500,
        msg: '用户名或者密码不正确！'
      }
    }
    console.log(111, res)
    ctx.cookies.set('userId', res._id, {
      path: '/',
      httpOnly: false,
      overwrite: false,
      maxAge: 10 * 60 * 1000 //ms
    })
    ctx.body = {
      code: 200,
      msg: '登录成功',
      data: res
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      msg: '登录失败'
    }
  }
})

module.exports = UserRouter